import React, { PropsWithChildren, useEffect } from 'react'
import { Form, Input, Modal, message as Message } from 'antd';
import { gql, useMutation, useLazyQuery } from '@apollo/client';

// 新增的graphql
const AddAccountGql = gql`
  mutation AddAccount($username: String!, $password: String!) {
    addAccount(username: $username, password: $password) {
      code
      message
    }
  }
`;

// 修改的graphql
const ModifyAccountGql = gql`
  mutation ModifyAccount($id:ID!, $username: String, $password: String) {
    modifyAccountById(id: $id, data: {username: $username, password: $password}) {
      code
      message
    }
  }
`;

// 根据id查询账号
const AccountGql = gql`
  query Account($id: ID!) {
    account(id: $id) {
      id
      username
      password
    }
  }
`;

const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};

type Props = PropsWithChildren<{
  isModalVisible: boolean;
  setIsModifyVisible: (isShow: boolean) => void;
  loadData: () => void;
  currentRowId?: number | undefined;
}>;
export const AccountModal: React.FC<Props> = (props: Props) => {
  const [form] = Form.useForm();
  const { isModalVisible, setIsModifyVisible, loadData, currentRowId } = props;
  // 创建的
  const [addAccount] = useMutation(AddAccountGql, {
    onCompleted: (data) => {
      const { addAccount: { code, message } } = data;
      if (Object.is(code, 0)) {
        Message.success(message);
        // 告诉父组件更新数据
        loadData();
        setIsModifyVisible(false);
      } else {
        Message.error(message);
      }
    }
  });
  // 更新的
  const [modifyAccount] = useMutation(ModifyAccountGql, {
    onCompleted: (data) => {
      const { modifyAccountById: { code, message } } = data;
      if (Object.is(code, 0)) {
        Message.success(message);
        // 告诉父组件更新数据
        loadData();
        setIsModifyVisible(false);
      } else {
        Message.error(message);
      }
    }
  })
  // 查询数据
  const [getAccount] = useLazyQuery(AccountGql, {
    onCompleted: (data) => {
      const { account: { username, password } } = data;
      form.setFieldsValue({
        username,
        password,
      })
    }
  });


  // 监听id的变化给表单赋值
  useEffect(() => {
    if (currentRowId) {
      getAccount({
        variables: {
          id: currentRowId,
        }
      });
    } else {
      form.setFieldsValue({
        username: '',
        password: '',
      })
    }
  }, [currentRowId]);

  const handleOk = () => {
    form.validateFields(['username', 'password']).then(values => {
      const { username, password } = values;
      console.log(values, '提交数据');

      // 根据当前是否有id区分是新增还是编辑
      if (currentRowId) {
        modifyAccount({
          variables: {
            id: currentRowId,
            username,
            password,
          }
        });
      } else {
        // 提交数据
        addAccount({
          variables: {
            username,
            password,
          }
        });
      }
    });
  };
  const handleCancel = () => {
    setIsModifyVisible(false);
  };
  return (
    <Modal title={currentRowId? `编辑用户` : '新增用户'} visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
      <Form
        {...layout}
        form={form}
      >
        <Form.Item
          label="账号名称"
          name="username"
          rules={[{ required: true, message: '请输入账号名称!' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="密码"
          name="password"
          rules={[{ required: true, message: '请输入密码!' }]}
        >
          <Input.Password />
        </Form.Item>
      </Form>
    </Modal>
  )
}